#!/bin/bash
help(){
    echo "search.sh match_pattern [options]"
    echo "  match_pattern:"
    echo "    eg: search.sh test #在当前目录查找包含'test'的文件"
    echo "  options:"
    echo "    -h/-? #帮助文档"
    echo "    -d dir #指定目录查找，默认为当前目录"
    echo "    -n 10 #指定结果行数，默认显示10行"
}

if [[ "$1" == "-h" || "$1" == "-?" ]]; then
    help
    exit 0
fi

empty(){
    if [ -z "$1" -o "$1" == "-*" ]; then
        echo "true"
    else
        echo "false"
    fi
}
end(){
    echo -e "\e[1;31;41m[Error]\e[0m $1"
    exit 0
}
end_if_empty(){
  e=`empty $1`
  if [[ "$e" == "true" ]]; then
    end $2
  fi
}
dir=`pwd`
# search match_pattern.
search=$1
# show line count
lineCount=10
for (( i=2; i<=$#; i++ ));
do
  p=${@: $i:1}
  case $p in
  "-d")
    i=$(( $i + 1 ))
    v=${@: $i:1}
    end_if_empty $v "-d 需要目录。eg: -d ./test"
    dir=$v
  ;;
  "-n")
    i=$(( $i + 1 ))
    v=${@: $i:1}
    end_if_empty $v "-n 需要设置显示行数。eg: -n 10"
    lineCount=$(( $v + 1 ))
  ;;
  * )
    end "unsupport option: $p"
  ;;
  esac
done

if [ -z  "$search" ]; then
    end "match_pattern value is empty"
fi


let nu=0
export GREP_COLOR='1;33'
show(){
    if [ -z $2 ]; then 
        return
    fi
    nu=$(( $nu + 1 ))
    file=${2%%:*}
    let pos=$(( ${#file} + 1 ))
    line=${2: $pos:15}
    line=${line%%:*}
    pos=$(( $pos + ${#line} + 1 ))
    echo -e "[$nu]\e[1;34m $file\e[0m:\e[1;36m$line\e[0m"
    echo ${2: $pos} | grep "$search" --color=auto
}


results=`grep -A 0 -m $lineCount -w -n -H "$search" $dir -r`
if [ -z "$results" ]; then
    echo "match_pattern: $search not found"
    exit 0
fi

line=''
for res in $results; do
    file=${res%%:*}
    if [[ $res == '--' ]]; then
        # end line
        show $nu $line
        line=''
    else
        line="$line$res"
    fi
    #echo -e "\e[1;32m$file\e[0m"
    #echo "----"
done
if [ -n $line ]; then
    show $line
fi


